package hk.hku.hooku.servlet;

import hk.hku.hooku.db.UserDB;
import hk.hku.hooku.pojo.User;

import java.io.*;
import javax.servlet.http.*;
import javax.servlet.*;

public class LoginServlet extends HttpServlet implements Servlet {
	public LoginServlet() {
	}

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html;charset=gb2312");
		request.setCharacterEncoding("gb2312");
		String result = "";
		String username = request.getParameter("username");
		String psw = request.getParameter("password");
		HttpSession session = request.getSession();
		session.setAttribute("loginUser", "");
		PrintWriter writer=response.getWriter();
		if ((username == "") || (username == null) || (username.length() > 40)) {
			try {
				result = "Please input your Email (within 40 chars)";
				session.setAttribute("message", result);
				writer.write(result);
			} catch (Exception e) {
				e.printStackTrace();
			}
			return;
		}
		if ((psw == "") || (psw == null) || (psw.length() > 20)) {
			try {
				result = "Please input password";
				session.setAttribute("message", result);
				writer.write(result);
			} catch (Exception e) {
				e.printStackTrace();
			}
			return;
		}

		User user = UserDB.getFullUserByGmail(username);
		if (user != null && user.getPasswd().equals(psw)) { 
			session.setAttribute("username", username);
			session.setAttribute("loginUser", username);
			writer.write("success");
		} else {
			result="Wrong password";
			session.setAttribute("message", "Wrong password");
			writer.write(result);
		}
	}

	private static final long serialVersionUID = 1L;
}